/**
 * 虚拟键盘 
 * 
 * 使用示例：
 *     var KB = new KeyBoard().forAllInput();
 * 
 * 属性：
 *     无
 *     
 * 可用方法：
 *     forAllInput: 如：KB.forAllInput(), 执行此方法后，当页面上有的input被点击时会显示键盘，并把被点击input作为输入目标.
 *     inputTo: 指定键盘输入目标，如：KB.inputTo("#inputTest");
 *     
 * @author TanJiaJun
 * @contact t_jiajun@163.com
 * @version v1.0
 */
(function($,window){
	window.KeyBoard = Keyboard;
	//构造
	function Keyboard() {
		this.isforAllInput = false;
		this.init();
	}

	Keyboard.prototype.kbHtml = '<div class="tkb-box">'
			+ '<div class="key-row"><button class="tkb-key" data-shift="~">`</button><button class="tkb-key" data-shift="!">1</button><button class="tkb-key" data-shift="@">2</button><button class="tkb-key" data-shift="#">3</button><button class="tkb-key" data-shift="$">4</button><button class="tkb-key" data-shift="%">5</button><button class="tkb-key" data-shift="^">6</button><button class="tkb-key" data-shift="&">7</button><button class="tkb-key" data-shift="*">8</button><button class="tkb-key" data-shift="(">9</button><button class="tkb-key" data-shift=")">0</button><button class="tkb-key" data-shift="_">-</button><button class="tkb-key" data-shift="+">=</button><button class="tkb-key backspace">&nbsp;</button></div>'
			+ '<div class="key-row"><button class="tkb-key" data-shift="Q">q</button><button class="tkb-key" data-shift="W">w</button><button class="tkb-key" data-shift="E">e</button><button class="tkb-key" data-shift="R">r</button><button class="tkb-key" data-shift="T">t</button><button class="tkb-key" data-shift="Y">y</button><button class="tkb-key" data-shift="U">u</button><button class="tkb-key" data-shift="I">i</button><button class="tkb-key" data-shift="O">o</button><button class="tkb-key" data-shift="P">p</button><button class="tkb-key" data-shift="{">[</button><button class="tkb-key" data-shift="}">]</button><button class="tkb-key" data-shift="|">\\</button></div>'
			+ '<div class="key-row"><button class="tkb-key" data-shift="A">a</button><button class="tkb-key" data-shift="S">s</button><button class="tkb-key" data-shift="D">d</button><button class="tkb-key" data-shift="F">f</button><button class="tkb-key" data-shift="G">g</button><button class="tkb-key" data-shift="H">h</button><button class="tkb-key" data-shift="J">j</button><button class="tkb-key" data-shift="K">k</button><button class="tkb-key" data-shift="L">l</button><button class="tkb-key" data-shift=":">;</button><button class="tkb-key" data-shift="&quot;">\'</button><button class="tkb-key enter">Enter</button></div>'
			+ '<div class="key-row"><button class="tkb-key shift">shift</button><button class="tkb-key" data-shift="Z">z</button><button class="tkb-key" data-shift="X">x</button><button class="tkb-key" data-shift="C">c</button><button class="tkb-key" data-shift="V">v</button><button class="tkb-key" data-shift="B">b</button><button class="tkb-key" data-shift="N">n</button><button class="tkb-key" data-shift="M">m</button><button class="tkb-key" data-shift="&lt;">,</button><button class="tkb-key" data-shift="&gt;">.</button><button class="tkb-key" data-shift="?">/</button><button class="tkb-key">清空</button></div>'
			+ '<div class="key-row"><button class="tkb-key space">&nbsp;</button></div>'
			+ '</div>';
	Keyboard.prototype.ignoreInputTypes = "file,radio,checkbox,hidden,button,image,reset,submit";
	Keyboard.prototype.init = function(){
		var othis = this;
		if(othis.$init) return;

		othis.$init = $(othis.kbHtml).appendTo('body');

		othis.$init.on("click",function(e){
			e.stopPropagation();
		});
		$(document).on("click",function(e){
			if(e.target.tagName=="INPUT"){
				return;
			}
			othis.$init.hide();
		});
		
		othis.$init.on("click","button.tkb-key",function() {
			var $key = $(this);
			var inputValue = othis.$input.val();
			var value = $key.html();
			var shiftValue = $key.attr("data-shift");
			if(value == "shift"){
				$key.hasClass('selected') ? $key.removeClass('selected') : $key.addClass('selected');
				othis.$init.find("button.tkb-key").each(function(index, el) {
					var $this = $(this);
					var key = $this.html();
					var skey = $this.attr("data-shift");
					$this.html(skey);
					$this.attr("data-shift",key);
				});
				return;
			}else if("Enter" == value) {
				othis.$input.focus();
				return;
			}else if("清空" == value){
				othis.$input.val("");
				othis.$input.focus();
				return;
			}else if($key.hasClass('space')) {
				othis.$input.val(inputValue+" ");
				othis.$input.focus();
				return;
				
			}else if($key.hasClass('backspace')){
				othis.$input.val(inputValue.substr(0,inputValue.length-1));
				othis.$input.focus();
				return;
			}

			value=="&amp;" && (value="&");
			if(value == "&amp;"){
				value = "&";
			}else if(value=="&lt;"){
				value = "<";
			}else if(value=="&gt;"){
				value = ">";
			}

			othis.$input.val(inputValue+value);
			othis.$input.focus();
			
			
		});

		initTouchMove(othis);
		
		initMouseMove(othis);

	}
	
	Keyboard.prototype.forAllInput = function(){
		var othis = this;
		if(othis.isforAllInput == false){
			$(document).on("click","input",function(){
		    	othis.inputTo(this);
		    });
			othis.isforAllInput = true;
		}
		return othis;
	}

	Keyboard.prototype.inputTo = function(target) {
		this.$input = $(target);
		if(othis.ignoreInputTypes.indexOf(this.$input.attr("type"))>=0){
			return;
		}
		var $kbBox = this.$init;
		var left = ($(window).width() - $kbBox.outerWidth()) / 2;
		$kbBox.css("left",left+"px");
		$kbBox.show();
	}
	
	function initTouchMove(kb){
		var othis = kb;
		var $move = othis.$init;
		$move.on('touchstart', function (e) {
			window.ttt = e;
		    var touch = e.originalEvent.targetTouches[0];
		    othis.startPosition = {
		        x: touch.pageX - $move.offset().left,
		        y: touch.pageY - $move.offset().top
		    }
		});

		$move.on('touchmove', function (e) {
		    var touch = e.originalEvent.targetTouches[0];
		    othis.endPosition = {
		        x: touch.pageX,
		        y: touch.pageY
		    }

		    $move.css({
	            "left": (othis.endPosition.x - othis.startPosition.x) + "px",
	            "top": (othis.endPosition.y - othis.startPosition.y) + "px"
	        });
		});
	}
	
	function initMouseMove(kb){
		var othis = kb;
		var $move = othis.$init;
	    $move.bind('mousedown', start);
	    function start(e) {
	        var ol = $move.offset().left;
	        var ot = $move.offset().top;
	        othis.startX = e.pageX - ol;
	        othis.startY = e.pageY - ot;
	        $(document).bind({
	            'mousemove': move,
	            'mouseup': stop
	        });
	        return false;
	    }
	    function move(e) {
	        $move.css({
	            "left": (e.pageX - othis.startX),
	            "top": (e.pageY - othis.startY)
	        });
	        return false;
	    }
	    function stop() {
	        $(document).unbind({
	            'mousemove': move,
	            'mouseup': stop
	        });
	    }
	}
})(jQuery,window);